package com.atguigu.gmall.realtime.app.dwd.db;

import com.atguigu.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

/**
 * @author Felix
 * @date 2023/4/18
 * 交易域：加购事实表
 */
public class DwdTradeCartAdd {
    public static void main(String[] args) throws Exception {
        //TODO 1.基本环境准备
        //1.1 指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(4);
        //1.3 指定表执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        //TODO 2.检查点相关的设置(略)
        //TODO 3.从kafka的topic_db主题中读取数据并创建动态表
        tableEnv.executeSql(MyKafkaUtil.getTopicDbDDL("dwd_trade_cart_add"));
        //TODO 4.过滤出加购行为
        Table cartInfo = tableEnv.sqlQuery("select\n" +
            "    data['id'] id,\n" +
            "    data['user_id'] user_id,\n" +
            "    data['course_id'] course_id,\n" +
                " data['sold'] sold,\n"+
            //"    if(`type`='insert',data['sku_num'],cast((CAST(`data`['sku_num'] AS INT) - CAST(`old`['sku_num'] AS INT)) as string)) sku_num,\n" +
            "    ts\n" +
            //"from topic_db where `table`='cart_info' and (`type`='insert' \n" +
            //"or (`type`='update' and `old`['sku_num'] is not null and (CAST(`data`['sku_num'] AS INT)  > CAST(`old`['sku_num'] AS INT))))");
                "  from  topic_db where `table`='cart_info' and data['sold']='0'");
        tableEnv.createTemporaryView("cart_info",cartInfo);
         //tableEnv.executeSql("select * from cart_info").print();

        //TODO 5.将加购数据写到kafka主题中
        //5.1 创建一个动态表和要写入的主题进行映射
        tableEnv.executeSql("CREATE TABLE dwd_trade_cart_add (\n" +
            "    id string,\n" +
            "    user_id string,\n" +
            "    course_id string,\n" +
            "    sold string,\n" +
            "    ts string,\n" +
            "    PRIMARY KEY (id) NOT ENFORCED\n" +
            ") " + MyKafkaUtil.getUpsertKafkaDDL("dwd_trade_cart_add")
        );
        //5.2 写入
        tableEnv.executeSql("insert into dwd_trade_cart_add select * from cart_info");


    }
}
